package com.lehecai.core.search.api;

import net.sf.json.JSON;
import net.sf.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sunshow
 * filter实体
 */
public class SearchApiRequestFilter {

	private List<SearchApiRequestFilterItem> filterItemList = new ArrayList<SearchApiRequestFilterItem>();

    protected void addFilter(String type, String field, Object value) {
        // TODO 搜索服务需要限定查询字段的类型，只支持Integer和Long，可以实现部分默认转换器
        SearchApiRequestFilterItem filterItem = new SearchApiRequestFilterItem(type, field, value);
        this.filterItemList.add(filterItem);
    }

    public void addEqual(String field, Object value) {
        this.addFilter(SearchApiConstant.API_OP_EQUAL, field, value);
    }

    public void addGreaterEqual(String field, Object value) {
        this.addFilter(SearchApiConstant.API_OP_GREATER_EQUAL, field, value);
    }

    public void addLessEqual(String field, Object value) {
        this.addFilter(SearchApiConstant.API_OP_LESS_EQUAL, field, value);
    }

    public void addGreater(String field, Object value) {
        this.addFilter(SearchApiConstant.API_OP_GREATER, field, value);
    }

    public void addLess(String field, Object value) {
        this.addFilter(SearchApiConstant.API_OP_LESS, field, value);
    }

    public void addBetween(String field, Object lowValue, Object highValue) {
        this.addGreaterEqual(field, lowValue);
        this.addLessEqual(field, highValue);
    }

    public JSON toJSON() {
        // return value should be a JSONArray
        JSONArray jsonArray = new JSONArray();
        for (SearchApiRequestFilterItem filterItem : this.filterItemList) {
            jsonArray.add(filterItem.toJSON());
        }
        return jsonArray;
    }

    public List<SearchApiRequestFilterItem> getFilterItemList() {
        return filterItemList;
    }
}
